<template>
  <div class="app-container">
    <div class="content">
      <el-form :model="freForm" status-icon :rules="freRules" ref="freForm" label-width="100px" class="fre-form" size="mini">
        <el-form-item label="模板名称" prop="name">
          <el-input type="text" v-model="freForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="计费方式" prop="valuation_type">
          <span v-if="$route.query.id">{{freForm.valuation_type==3?'按件数':'按重量'}}</span>
          <el-radio-group @change="resetNumber()" v-else v-model="freForm.valuation_type">
            <el-radio :label="3">按件数</el-radio>
            <el-radio :label="2">按重量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="配送区域">
          <table class="fre-table sui-table table-bordered " style="width:900px">
            <thead>
              <tr>
                <th class="center">可配送区域</th>
                <th class="center">{{freForm.valuation_type === 3 ? '首件（个）' : '首重（kg）'}}</th>
                <th class="center">运费（元）</th>
                <th class="center">{{freForm.valuation_type === 3 ? '续件（个）' : '续重（kg）'}}</th>
                <th class="center">续费（元）</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in freForm.valuation_rules" :key="index">
                <td class="left-td">
                  <span v-for="area in item.regions" :key="area.id" class="area-title" :class="{'strong':area.pid==0}"> {{area.title}} </span>
                  <el-button type="text" size="small" @click="handleAreaEdit(index)">编辑</el-button>
                  <el-button type="text" size="small" @click="handleAreaDel(index)">删除</el-button>
                </td>
                <td class="center">
                  <!--<el-form-item :prop="'first_amount'+index" :rules="freRules.first_amount">-->
                  <!--<div v-if="freForm.valuation_type=='3'" class="el-input el-input--mini">
                    <input type="text" autocomplete="off" v-model="item.first_amount" class="">
                  </div>-->
                  <div class="el-input el-input--mini">
                    <input v-if="freForm.valuation_type=='2'" type="text" autocomplete="off" @blur="FormateMoney(index,'first_amount',2)" v-model="item.first_amount"
                      class="el-input__inner">
                    <input v-else type="text" autocomplete="off" @blur="FormateMoney(index,'first_amount',0)" v-model="item.first_amount" class="el-input__inner">
                  </div>
                  <!--</el-form-item>-->
                </td>
                <td class="center">
                  <div class="el-input el-input--mini">
                    <input type="text" autocomplete="off" @blur="FormateMoney(index,'first_fee',2)" v-model="item.first_fee" class="el-input__inner">
                  </div>
                </td>
                <td class="center">
                  {{item.additional_amount}}
                </td>
                <td class="center">
                  <div class="el-input el-input--mini">
                    <input type="text" autocomplete="off" @blur="FormateMoney(index,'additional_fee',2)" v-model="item.additional_fee" class="el-input__inner">
                  </div>
                </td>
              </tr>

              <!--<tr v-for="(item,index) in freForm.valuation_rules" :key="index">
                <template>
                  <td class="left-td">
                    <span v-for="area in item.regions" :key="area.id" class="area-title" :class="{'strong':area.pid==0}"> {{area.title}} </span>
                    <el-button type="text" size="small" @click="handleAreaEdit(index)">编辑</el-button>
                    <el-button type="text" size="small" @click="handleAreaDel(index)">删除</el-button>
                  </td>
                  <td class="center">
                    <el-input type="text" size="mini" v-model="item.first_amount" auto-complete="off"></el-input>
                  </td>
                  <td class="center">
                    <el-input type="text" size="mini" v-model="item.first_fee" auto-complete="off"></el-input>
                  </td>
                  <td class="center">
                    {{item.additional_amount}}
                  </td>
                  <td class="center">
                    <el-input type="text" size="mini" v-model="item.additional_fee" auto-complete="off"></el-input>
                  </td>
                </template>

              </tr>-->
            </tbody>
            <tfoot>
              <tr>
                <td colspan="5">
                  <el-button type="text" size="small" @click="handleAdd">指定可配送区域和运费</el-button>
                </td>
              </tr>
            </tfoot>
          </table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('freForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--address dialog-->
    <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="630px" center
      :before-close="handleClose">
      <synctree v-if="reloadTree" :data.sync="tempList" v-model="finalData"></synctree>
      <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="handleAreaSubmit(false)">保 存</el-button>
      </span>
    </el-dialog>
    <!--address dialog-->
  </div>
</template>

<script>
  import Synctree from '@/components/Synctree'
  import originData from '@/components/Synctree/data'
  import {
    mapGetters
  } from 'vuex'
  import {
    getFreightDetail,
    addFreight,
    editFreight
  } from '@/api/freight'
  import {
    deepClone,
    formatNumber
  } from '@/utils'
  import {} from '@/api/freight'
  export default {
    components: {
      Synctree
    },
    data() {
      return {
        reloadTree: false,
        originData: originData,
        tempList: [],
        disabledKeys: [],
        templateId: this.$route.query.id,
        dialogVisible: false,
        first: true,
        finalData: [],
        tempData: [],
        editFlag: false,
        editIndex: null,
        freForm: {
          valuation_rules: [],
          name: '',
          valuation_type: 3
        },
        valuationItem: {
          regions: [],
          first_amount: 1,
          first_fee: '0.00',
          additional_amount: '1',
          additional_fee: '0.00'
        },
        editKeys: [],
        tempKeys: [],
        freRules: {
          name: [{
            required: true,
            message: '请输入模版名称',
            trigger: 'blur'
          }],
          first_amount: [{
            type: 'number',
            message: '请输入数字',
            trigger: 'blur'
          }]
        }
      }
    },

    computed: {
      ...mapGetters({
        // disabledKeys: 'dis_tree',
        abledKeys: 'able_tree'
      })
    },
    methods: {
      handleClose() { // 右上角关闭操作
        this.handleAreaSubmit(true)
      },
      FormateMoney(index, key, cent) {
        this.freForm.valuation_rules[index][key] = formatNumber(this.freForm.valuation_rules[index][key], cent)
      },
      // 重置运费
      resetNumber() {
        this.freForm.valuation_rules.forEach(item => {
          item.first_amount = 1
          item.first_fee = '0.00'
          item.additional_amount = '1'
          item.additional_fee = '0.00'
        })
      },
      submitForm(formName) {
        // console.log(JSON.stringify(this.freForm))
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const formData = deepClone(this.freForm)
            // 判断是否有配送区域
            if (formData.valuation_rules.length <= 0) {
              this.$message.error('至少要有一个配送区域')
              return false
            }
            formData.name = encodeURI(formData.name)
            formData.valuation_rules.forEach(item => {
              item.regions.forEach(key => {
                key.title = encodeURI(key.title)
              })
            })
            // 编辑
            if (this.templateId) {
              formData.templateId = this.templateId
              editFreight(formData).then(response => {
                this.$message({
                  message: '更新成功',
                  type: 'success'
                })
              }).catch(() => {})
            } else {
              // 添加
              addFreight(formData).then(response => {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
              }).catch(() => {})
            }
            this.$router.push({
              name: 'freight'
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 点击添加，编辑配送区域
      handleAdd() {
        this.reloadTree = true
        this.tempList = deepClone(this.originData)
        // 设置不可选
        this.disabledKeys.forEach(key => {
          this.tempList.forEach(item => {
            if (key === item.id) {
              this.$set(item, 'disabled', true)
            }
          })
        })
        this.dialogVisible = true
      },
      // 提交配送区域
      handleAreaSubmit(cancel) {
        // if (!cancel && this.finalData <= 0) {
        //   this.dialogVisible = false
        //   return false
        // }
        // 如果编辑地址
        if (this.editIndex !== null) {
          // 如果取消添加恢复到原来数据
          const finalData = cancel ? this.tempData : this.finalData
          // 判断是否为空
          if (finalData.length <= 0) {
            this.$message.error('请至少选一个配送区域')
            return false
          }
          // 更新编辑数据
          this.freForm.valuation_rules[this.editIndex].regions = finalData
          // 编辑id重置
          this.editIndex = null
        } else {
          const temp = {
            regions: this.finalData,
            first_amount: 1,
            first_fee: '0.00',
            additional_amount: '1',
            additional_fee: '0.00'
          }
          // 添加一行数据
          if (this.finalData.length > 0) {
            this.freForm.valuation_rules.push(temp)
          }
        }
        // 如果是取消disabled不变
        if (cancel) {
          this.disabledKeys = this.tempKeys
        } else {
          this.abledKeys.forEach(item => {
            this.disabledKeys.push(item)
          })
          this.tempKeys = deepClone(this.disabledKeys)
        }

        // 清空选择地址数据，为下次添加准备
        this.finalData = []
        this.dialogVisible = false
        this.reloadTree = false
      },
      findOut(target, arg) {
        return target.filter(v => !arg.includes(v))
      },
      // 编辑选择配送区域
      handleAreaEdit(index) {
        this.editIndex = index
        this.reloadTree = true
        this.finalData = this.freForm.valuation_rules[index].regions
        // 复制，当用户取消时候恢复用
        this.tempData = deepClone(this.finalData)
        const abledKeys = []
        this.finalData.forEach(item => {
          abledKeys.push(item.id)
        })
        // 备份编辑前disabledKeys,用户取消时恢复
        // this.tempKeys = deepClone(this.disabledKeys)
        this.disabledKeys = this.findOut(this.disabledKeys, abledKeys)
        // 重新加载弹框
        this.handleAdd()
      },
      // 删除选择配送区域
      handleAreaDel(index) {
        this.$confirm('确定要删除此条记录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const delKeys = []
          this.freForm.valuation_rules[index].regions.forEach(item => {
            delKeys.push(item.id)
          })
          this.disabledKeys = this.findOut(this.disabledKeys, delKeys)
          this.freForm.valuation_rules.splice(index, 1)
        }).catch(() => {

        })
      },
      init() {
        if (this.templateId) {
          const formData = {
            templateId: this.templateId
          }
          // 获取运费详情
          getFreightDetail(formData).then(res => {
            this.freForm = res.data.supplierFreightDetails
            // 不可选地址
            this.freForm.valuation_rules.forEach(item => {
              item.regions.forEach(key => {
                this.disabledKeys.push(key.id)
              })
              // 格式化金额
              item.additional_fee = this.$options.filters.formatMoney(item.additional_fee)
              item.first_fee = this.$options.filters.formatMoney(item.first_fee)
            })
          })
        }
      }
    },
    mounted() {
      this.init()
    }
  }

</script>
<style rel="stylesheet/scss" lang="scss">
  @import 'src/assets/css/sui.scss';
  .fre-form {
    .el-input,
    .el-textarea {
      width: 320px
    }
  }

  .fre-table {
    td {
      .area-title {
        color: #999999;
        &.strong {
          color: #000;
        }
      }
      .el-input {
        width: 100px;
        input {
          text-align: center;
        }
      }
    }
  }

</style>
